package com.vichat.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.constant.MessageConstants;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.vo.PageFilter;
import com.vichat.core.dao.BaseDaoI;
import com.vichat.user.entity.SecFunction;
import com.vichat.user.entity.SecRole;
import com.vichat.user.entity.SecRoleFunction;
import com.vichat.user.service.ISecService;
import com.vichat.user.vo.MenuVO;
import com.vichat.user.vo.Privilege;
import com.vichat.user.vo.PrivilegeVO;
import com.vichat.user.vo.RoleMenuVO;
import com.vichat.user.vo.SecRoleFuncVO;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/11/15.
 */
@Service("secService")
public class SecServiceImpl implements ISecService {
    protected static final Logger logger = LoggerFactory.getLogger(SecServiceImpl.class);
    @Autowired
    private BaseDaoI<SecRole> secRoleDao;
    @Autowired
    private BaseDaoI<SecFunction> secFuncDao;
    @Autowired
    private BaseDaoI<SecRoleFunction> secRoleFunctionDao;

    /**
     * 拼装排序字段
     *
     * @param pf
     * @return
     */
    private String orderHql(PageFilter pf) {
        String orderString = "";
        if (pf != null) {
            if ((pf.getSort() != null) && (pf.getOrder() != null)) {
                orderString = " order by " + pf.getSort() + " " + pf.getOrder();
            }
        }
        return orderString;
    }

    /**
     * 查询角色信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    public List<SecRole> querySecRole(SecRole queryBean, PageFilter pf) {
        HashMap params = new HashMap();
        String hql = "from SecRole where  state=1  ";
        if (NumberUtils.isNotNullOrZero(queryBean.getRoid())) {
            hql += " and roid = :roid";
            params.put("roid", queryBean.getRoid());
        }
        if (NumberUtils.isNotNullOrZero(queryBean.getPartyId())) {
            hql += " and partyId like :partyId";
            params.put("partyId", queryBean.getPartyId());
        }
        if (StringUtils.isNotBlank(queryBean.getRoleName())) {
            hql += " and roleName like :roleName";
            params.put("roleName", "%" + queryBean.getRoleName() + "%");
        }

        List<SecRole> secRoles = secRoleDao.find(hql + orderHql(pf), params, pf.getPage(), pf.getLimit());
        return secRoles;
    }

    /**
     * 查询角色信息（无参数）
     *
     * @return
     */
    public List<SecRole> querySecRole() {
        HashMap params = new HashMap();
        String hql = "from SecRole where  state=1  ";
        hql += " order by roid";

        List<SecRole> secRoles = secRoleDao.find(hql, params);
        return secRoles;
    }

    /**
     * 查询角色数量
     *
     * @param queryBean
     * @return
     * @throws Exception
     */
    public Long countSecRole(SecRole queryBean) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = "select count(*) from SecRole where state = 1";
        if (NumberUtils.isNotNullOrZero(queryBean.getRoid())) {
            hql += " and roid like :roid";
            params.put("roid", "%" + queryBean.getRoid() + "%");
        }
        if (NumberUtils.isNotNullOrZero(queryBean.getPartyId())) {
            hql += " and partyId like :partyId";
            params.put("partyId", queryBean.getPartyId());
        }
        if (StringUtils.isNotBlank(queryBean.getRoleName())) {
            hql += " and roleName like :roleName";
            params.put("roleName", "%" + queryBean.getRoleName() + "%");
        }
        return secRoleDao.count(hql, params);
    }

    /**
     * 根据角色编号获取角色信息
     *
     * @param roid
     * @return
     */
    public SecRole querySecRoleByRoid(Long roid) {
        SecRole secRoleFDB = null;
        String jsonStr = RedisHelper.getSecRole(roid);
        if (StringUtils.isNotBlank(jsonStr)) {
            secRoleFDB = JSONObject.parseObject(jsonStr, SecRole.class);
        } else {
            if (NumberUtils.isNotNullOrZero(roid)) {
                secRoleFDB = secRoleDao.get(SecRole.class, roid);
                if (secRoleFDB != null)
                    RedisHelper.setSecRole(secRoleFDB.getRoid(), JSONObject.toJSONString(secRoleFDB));
            }
        }
        return secRoleFDB;
    }

    /**
     * 根据角色编号删除角色
     *
     * @param roid
     */
    public void delSecRole(Long roid) {
        SecRole secRoleFDB = this.querySecRoleByRoid(roid);
        if (secRoleFDB != null) {
            secRoleDao.deleted(secRoleFDB);
            RedisHelper.delSecRole(roid);
        }
    }

    /**
     * 添加或者修改角色
     *
     * @param secRole
     * @throws Exception
     */
    @Override
    public void saveOrUpdSecRole(SecRole secRole) throws Exception {
        SecRole secRoleFDB = this.querySecRoleByRoid(secRole.getRoid());
        if (secRoleFDB == null) {
            secRoleDao.save(secRole);
            RedisHelper.setSecRole(secRole.getRoid(), JSONObject.toJSONString(secRole));
        } else {
            secRoleFDB.setRoid(secRole.getRoid());
            secRoleFDB.setRoleName(secRole.getRoleName());
            secRoleFDB.setRoleDesc(secRole.getRoleDesc());
            secRoleDao.update(secRoleFDB);
            RedisHelper.setSecRole(secRole.getRoid(), JSONObject.toJSONString(secRoleFDB));
        }
    }

    /**
     * 查询菜单信息
     * 无参数
     *
     * @return
     */
    public List<SecFunction> querySecFunction() {
        HashMap params = new HashMap();
        String hql = "from SecFunction where  state=1  ";
        hql += " order by sortno";

        List<SecFunction> secFuncs = secFuncDao.find(hql, params);
        return secFuncs;
    }

    /**
     * 查询菜单信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    public List<SecFunction> querySecFunction(SecFunction queryBean, PageFilter pf) {
        HashMap params = new HashMap();
        String hql = "from SecFunction where  state=1  ";
        if (NumberUtils.isNotNullOrZero(queryBean.getFid())) {
            hql += " and fid like :fid";
            params.put("fid", "%" + queryBean.getFid() + "%");
        }
        if (StringUtils.isNotBlank(queryBean.getFuncName())) {
            hql += " and funcName like :funcName";
            params.put("funcName", "%" + queryBean.getFuncName() + "%");
        }
        if (NumberUtils.isNotNullOrZero(queryBean.getParentFid())) {
            hql += " and ( parentFid = :parentFid or fid =:parentFid)";
            params.put("parentFid", queryBean.getParentFid());
        }
        List<SecFunction> secFuncs = secFuncDao.find(hql + orderHql(pf), params, pf.getPage(), pf.getRows());
        return secFuncs;
    }

    /**
     * 查询菜单数量
     *
     * @param queryBean
     * @return
     * @throws Exception
     */

    public Long countSecFunction(SecFunction queryBean) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = "select count(*) from SecFunction where state = 1";
        if (NumberUtils.isNotNullOrZero(queryBean.getFid())) {
            hql += " and fid like :fid";
            params.put("fid", "%" + queryBean.getFid() + "%");
        }
        if (StringUtils.isNotBlank(queryBean.getFuncName())) {
            hql += " and funcName like :funcName";
            params.put("funcName", "%" + queryBean.getFuncName() + "%");
        }
        if (NumberUtils.isNotNullOrZero(queryBean.getParentFid())) {
            hql += " and ( parentFid = :parentFid or fid =:parentFid)";
            params.put("parentFid", queryBean.getParentFid());
        }
        return secFuncDao.count(hql, params);
    }

    /**
     * 根据菜单编号获取菜单信息
     *
     * @param fid
     * @return
     */
    public SecFunction querySecFuncByFid(Long fid) {
        SecFunction secFuncFDB = null;
        String jsonStr = RedisHelper.getSecFunc(fid);
        if (StringUtils.isNotBlank(jsonStr)) {
            secFuncFDB = JSONObject.parseObject(jsonStr, SecFunction.class);
        } else {
            if (NumberUtils.isNotNullOrZero(fid)) {
                secFuncFDB = secFuncDao.get(SecFunction.class, fid);
                RedisHelper.setSecFunc(secFuncFDB.getFid(), JSONObject.toJSONString(secFuncFDB));
            }
        }
        return secFuncFDB;
    }

    /**
     * 添加或者修改菜单
     *
     * @param secFunc
     * @throws Exception
     */
    @Override
    public void saveOrUpdSecFunc(SecFunction secFunc) throws Exception {
        SecFunction secFuncFDB = this.querySecFuncByFid(secFunc.getFid());
        if (secFuncFDB == null) {
            secFuncDao.save(secFunc);
            RedisHelper.setSecFunc(secFunc.getFid(), JSONObject.toJSONString(secFunc));
        } else {
            secFuncFDB.setFid(secFunc.getFid());
            secFuncFDB.setFuncName(secFunc.getFuncName());
            secFuncFDB.setFuncDesc(secFunc.getFuncDesc());
            secFuncFDB.setFuncUrl(secFunc.getFuncUrl());
            secFuncFDB.setFuncPic(secFunc.getFuncPic());
            secFuncFDB.setFuncLevel(secFunc.getFuncLevel());
            secFuncFDB.setParentFid(secFunc.getParentFid());
            secFuncFDB.setSortno(secFunc.getSortno());
            secFuncDao.update(secFuncFDB);
            RedisHelper.setSecFunc(secFunc.getFid(), JSONObject.toJSONString(secFuncFDB));
        }
    }

    /**
     * 根据菜单编号删除菜单
     *
     * @param fid
     */
    public void delSecFunc(Long fid) {
        SecFunction secFuncFDB = this.querySecFuncByFid(fid);
        if (secFuncFDB != null) {
            secFuncDao.deleted(secFuncFDB);
            RedisHelper.delSecFunc(fid);
        }
    }

    /**
     * 根据一级菜单编号查询其是否有二级菜单
     */
    public Boolean IsFirstFunc(Long fid) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = "select count(*) from SecFunction where  state=1  ";
        if (NumberUtils.isNotNullOrZero(fid)) {
            hql += " and parentFid = :parentFid";
            params.put("parentFid", fid);
        }
        return secFuncDao.count(hql, params) > 0 ? true : false;
    }

    /**
     * 根据角色编号获取菜单分配信息
     *
     * @param uid
     * @return
     */
    public List<SecRoleFuncVO> querySecRoleFuncVOByUid(Long uid, long state) {
        List<SecRoleFuncVO> secRoleFuncVOS = new ArrayList<SecRoleFuncVO>();//分配菜单数据集合
        SecRoleFuncVO secRoleFuncVO = null;
        HashMap params = new HashMap();

        List<SecRoleFunction> secRoleFunctions = null;
        String sql = "select a.* from userdb.sec_role_function a,userdb.user_basic b,userdb.user_sec_role_rel c where  a.state=1 and  a.roid = c.roid and b.uid = c.uid";
        if (NumberUtils.isNotNullOrZero(uid)) {
            sql += " and b.uid = :uid";
            params.put("uid", uid);
        }
        sql += " order by a.roid, a.fid";
        secRoleFunctions = secRoleFunctionDao.findEntityBySql(sql, params, SecRoleFunction.class);
        //获取一级菜单信息
        HashMap params2 = new HashMap();
        params2.put("state",state);
        String hql = "from SecFunction where funcType = 1 and state=:state and funcLevel =1 order by sortno";
        List<SecFunction> secFirstFunctions = secFuncDao.find(hql,params2);
        //获取二级菜单信息
        hql = "from SecFunction where funcType = 1 and state=:state and funcLevel =2 order by sortno";
        List<SecFunction> secSecondFunctions = secFuncDao.find(hql,params2);
        List<SecFunction> secFuncSeconds = null;
        if (secFirstFunctions != null) {//一级菜单数据非空
            for (SecFunction secFirstFunction : secFirstFunctions) {//遍历一级菜单
                secRoleFuncVO = new SecRoleFuncVO();
                for (SecRoleFunction secRoleFunction : secRoleFunctions) {//遍历一级菜单勾选数据
                    if (secRoleFunction.getFid().intValue() == secFirstFunction.getFid().intValue()) {
                        secFirstFunction.setIsChecked(true);
                        break;
                    }
                }
                secRoleFuncVO.setFristFunc(secFirstFunction);
                if (secSecondFunctions != null) {//二级菜单数据非空
                    secFuncSeconds = new ArrayList<>();
                    for (SecFunction secSecondFunction : secSecondFunctions) {//遍历二级菜单数据
                        if (secFirstFunction.getFid().intValue() == secSecondFunction.getParentFid().intValue()) {//根据一级菜单编号筛选相关的二级菜单数据
                            for (SecRoleFunction secRoleFunction : secRoleFunctions) {//遍历二级菜单勾选数据
                                if (secRoleFunction.getFid().intValue() == secSecondFunction.getFid().intValue()) {
                                    secSecondFunction.setIsChecked(true);
                                    break;
                                }
                            }
                            secFuncSeconds.add(secSecondFunction);
                        }
                    }
                    secRoleFuncVO.setSecondFuncList(secFuncSeconds);
                }
                secRoleFuncVOS.add(secRoleFuncVO);
            }
        }
        return secRoleFuncVOS;
    }

    /**
     * 根据角色编号获取菜单分配信息
     *
     * @param roid
     * @return
     */
    public List<SecFunction> querySecRoleFuncVOByRoid(Long roid) {
        HashMap params = new HashMap();
        String hql = "";

        List<SecRoleFunction> secRoleFunctions = null;
        hql = "from SecRoleFunction where  state=1  ";
        if (NumberUtils.isNotNullOrZero(roid)) {
            hql += " and roid = :roid";
            params.put("roid", roid);
        }
        hql += " order by roid, fid";
        secRoleFunctions = secRoleFunctionDao.find(hql, params);
        //获取一级菜单信息
        hql = "from SecFunction where  state=1  order by sortno";
        List<SecFunction> secFirstFunctions = secFuncDao.find(hql);
        if (secFirstFunctions != null) {//一级菜单数据非空
            for (SecFunction secFirstFunction : secFirstFunctions) {//遍历一级菜单
                for (SecRoleFunction secRoleFunction : secRoleFunctions) {//遍历一级菜单勾选数据
                    if (secRoleFunction.getFid().intValue() == secFirstFunction.getFid().intValue()) {
                        secFirstFunction.setIsChecked(true);
                        break;
                    }
                }
            }
        }
        return secFirstFunctions;
    }

    @Override
    public List<MenuVO> queryAllMenuTree(Long roleId) {
        String hql = "";
        HashMap params = new HashMap();
        hql = "from SecRoleFunction where state=1  ";
        if (NumberUtils.isNotNullOrZero(roleId)) {
            hql += " and roid = :roid";
            params.put("roid", roleId);
        }
        hql += " order by roid, fid";
        //当前角色下已经分配的菜单
        List<SecRoleFunction> secRoleFunctions = secRoleFunctionDao.find(hql, params);

        //获取一级菜单信息
        List<SecFunction> secFirstFunctions = getMenus(GlobalConstant.SEC_FUN_LEVEL_1, null);

        List<MenuVO> firstList = new ArrayList<MenuVO>();
        //遍历一级菜单
        for (SecFunction secFirstFunction : secFirstFunctions) {
            MenuVO first = new MenuVO();
            first.setTitle(secFirstFunction.getFuncName());
            first.setValue(String.valueOf(secFirstFunction.getFid()));
            //遍历勾选数据
            for (SecRoleFunction secRoleFunction : secRoleFunctions) {
                if (secRoleFunction.getFid().intValue() == secFirstFunction.getFid().intValue()) {
                    first.setChecked(true);
                    break;
                }
            }

            //二级菜单
            List<MenuVO> secondList = new ArrayList<MenuVO>();
            //获取二级菜单信息
            List<SecFunction> secSecondFunctions = getMenus(GlobalConstant.SEC_FUN_LEVEL_2, secFirstFunction.getFid());
            for (SecFunction secSecondFunction : secSecondFunctions) {
                MenuVO second = new MenuVO();
                second.setTitle(secSecondFunction.getFuncName());
                second.setValue(String.valueOf(secSecondFunction.getFid()));
                //遍历勾选数据
                for (SecRoleFunction secRoleFunction : secRoleFunctions) {
                    if (secRoleFunction.getFid().intValue() == secSecondFunction.getFid().intValue()) {
                        second.setChecked(true);
                        break;
                    }
                }

                //三级菜单
                List<MenuVO> threeList = new ArrayList<MenuVO>();
                //三级菜单信息
                List<SecFunction> secThreeFunctions = getMenus(GlobalConstant.SEC_FUN_LEVEL_3, secSecondFunction.getFid());
                for (SecFunction secThreeFunction : secThreeFunctions) {
                    MenuVO three = new MenuVO();
                    three.setTitle(secThreeFunction.getFuncName());
                    three.setValue(String.valueOf(secThreeFunction.getFid()));
                    //遍历勾选数据
                    for (SecRoleFunction secRoleFunction : secRoleFunctions) {
                        if (secRoleFunction.getFid().intValue() == secThreeFunction.getFid().intValue()) {
                            three.setChecked(true);
                            break;
                        }
                    }
                    threeList.add(three);
                }
                second.setData(threeList);
                secondList.add(second);
            }

            first.setData(secondList);
            firstList.add(first);
        }
        return firstList;
    }

    @Override
    public void saveSecRoleFunction(RoleMenuVO roleMenuVO) {
        Long roleId = Long.parseLong(roleMenuVO.getRoleId());
        String hql = "delete from SecRoleFunction where state=1 and roid=" + roleId;
        if (secRoleFunctionDao.executeHql(hql) > 0) {
            RedisHelper.delSecRoleFunc(roleId);
        }
        for (String str : roleMenuVO.getList()) {
            SecRoleFunction secRoleFunction = new SecRoleFunction();
            secRoleFunction.setRoid(roleId);
            secRoleFunction.setFid(Long.parseLong(str));
            secRoleFunctionDao.save(secRoleFunction);
        }

        List<SecRoleFunction> secRoleFuncFDBs = new ArrayList<SecRoleFunction>();
        //遍历菜单时用以保存的对象
        SecRoleFunction secRoleFunction = null;
        List<PrivilegeVO> privilegeVOS = new ArrayList<>();//左侧菜单
        //获取一级菜单信息
        List<SecFunction> secFirstFunctions = getMenus(GlobalConstant.SEC_FUN_LEVEL_1, null);
        for (SecFunction secFunction : secFirstFunctions) {
            // 保存一级菜单中勾选的数据 start
            secRoleFunction = new SecRoleFunction();
            secRoleFunction.setRoid(roleId);
            secRoleFunction.setFid(secFunction.getFid());
            secRoleFuncFDBs.add(secRoleFunction);

            // 保存一级菜单中勾选的数据用做左侧菜单 start
            PrivilegeVO privilegeVO = new PrivilegeVO();
            SecFunction funcNameOther = querySecFuncByFid(secFunction.getFid());
            privilegeVO.setTitle(funcNameOther.getFuncName());
            privilegeVO.setIcon(funcNameOther.getFuncPic());
            privilegeVO.setHref(funcNameOther.getFuncUrl());
            privilegeVO.setSpread(false);

            List<Privilege> privilegeSeconds = new ArrayList<>();
            //获取二级菜单信息
            List<SecFunction> secSecondFunctions = getMenus(GlobalConstant.SEC_FUN_LEVEL_2, secFunction.getFid());
            for (SecFunction secondFunc : secSecondFunctions) {
                // 保存二级菜单中勾选的数据 start
                secRoleFunction = new SecRoleFunction();
                secRoleFunction.setRoid(roleId);
                secRoleFunction.setFid(secondFunc.getFid());

                // 保存二级菜单中勾选的数据用做左侧菜单 start
                Privilege privilegeSecond = new Privilege();
                funcNameOther = querySecFuncByFid(secondFunc.getFid());
                privilegeSecond.setTitle(funcNameOther.getFuncName());
                privilegeSecond.setIcon(funcNameOther.getFuncPic());
                privilegeSecond.setHref(funcNameOther.getFuncUrl());
                privilegeSecond.setSpread(false);
                privilegeSeconds.add(privilegeSecond);//二级菜单赋值
            }
            if (!privilegeSeconds.isEmpty()) {
                privilegeVO.setChildren(privilegeSeconds);
            }
            privilegeVOS.add(privilegeVO);

        }
        RedisHelper.setSecRoleFunc(roleId, JSONObject.toJSONString(secRoleFuncFDBs));
        RedisHelper.setSecPrivilege(roleId, JSONObject.toJSONString(privilegeVOS));
    }

    /**
     * @param
     * @return
     * @throws
     * @Title: getMenus
     * @Description: 获取菜单数据根据级别
     */
    @Override
    public List<SecFunction> getMenus(Long funcLevel, Long parentFid) {
        HashMap params = new HashMap();
        String hql = "from SecFunction where state=1 ";
        if (funcLevel != null) {
            hql += " and funcLevel =:funcLevel";
            params.put("funcLevel", funcLevel);
        }
        if (parentFid != null) {
            hql += " and parentFid =:parentFid";
            params.put("parentFid", parentFid);
        }
        hql += " order by sortno";
        return secFuncDao.find(hql, params);
    }

    /**
     * 添加或者修改分配菜单数据
     *
     * @param secRoleFuncVos
     * @throws Exception
     */
    @Override
    public void saveOrUpSecRoleFunction(List<SecRoleFuncVO> secRoleFuncVos) throws Exception {
        Long roid = secRoleFuncVos.get(0).getRoid();//角色编号
        List<SecRoleFunction> secRoleFuncFDBs = this.querySecRoleFunctionByRoid(roid);//根据角色编号获取已勾选菜单信息

        if (secRoleFuncFDBs != null && secRoleFuncFDBs.size() > 0) {//修改
            HashMap params = new HashMap();
            String hql = "delete from SecRoleFunction where  state=1  ";
            if (NumberUtils.isNotNullOrZero(roid)) {
                hql += " and roid = :roid";
                params.put("roid", roid);
            }
            if (secRoleFunctionDao.executeHql(hql, params) > 0) {
                RedisHelper.delSecRoleFunc(roid);
            }
        }
        if (secRoleFuncVos != null) {//所有已勾选的菜单数据
            SecRoleFunction secRoleFunction = null;//遍历菜单时用以保存的对象
            secRoleFuncFDBs = new ArrayList<SecRoleFunction>();

            List<PrivilegeVO> privilegeVOS = new ArrayList<>();//左侧菜单
            for (SecRoleFuncVO secRoleFuncVO : secRoleFuncVos) {

                // 保存一级菜单中勾选的数据 start
                secRoleFunction = new SecRoleFunction();
                secRoleFunction.setRoid(roid);
                secRoleFunction.setFid(secRoleFuncVO.getFristFunc().getFid());
                secRoleFunctionDao.save(secRoleFunction);
                secRoleFuncFDBs.add(secRoleFunction);
                // 保存一级菜单中勾选的数据 end

                // 保存一级菜单中勾选的数据用做左侧菜单 start
                PrivilegeVO privilegeVO = new PrivilegeVO();
                SecFunction funcNameOther = querySecFuncByFid(secRoleFuncVO.getFristFunc().getFid());
                privilegeVO.setTitle(funcNameOther.getFuncName());
                privilegeVO.setIcon(funcNameOther.getFuncPic());
                privilegeVO.setHref(funcNameOther.getFuncUrl());
                privilegeVO.setSpread(false);
                // 保存一级菜单中勾选的数据左侧菜单 end

                List<Privilege> privilegeSeconds = new ArrayList<>();
                for (SecFunction SecondFunc : secRoleFuncVO.getSecondFuncList()) {

                    // 保存二级菜单中勾选的数据 start
                    secRoleFunction = new SecRoleFunction();
                    secRoleFunction.setRoid(roid);
                    secRoleFunction.setFid(SecondFunc.getFid());
                    secRoleFunctionDao.save(secRoleFunction);
                    secRoleFuncFDBs.add(secRoleFunction);
                    // 保存二级菜单中勾选的数据 end

                    // 保存一级菜单中勾选的数据用做左侧菜单 start
                    Privilege privilegeSecond = new Privilege();
                    funcNameOther = querySecFuncByFid(SecondFunc.getFid());
                    privilegeSecond.setTitle(funcNameOther.getFuncName());
                    privilegeSecond.setIcon(funcNameOther.getFuncPic());
                    privilegeSecond.setHref(funcNameOther.getFuncUrl());
                    privilegeSecond.setSpread(false);
                    privilegeSeconds.add(privilegeSecond);//二级菜单赋值
                    // 保存一级菜单中勾选的数据左侧菜单 end
                }
                if (!privilegeSeconds.isEmpty()) {
                    privilegeVO.setChildren(privilegeSeconds);
                }
                privilegeVOS.add(privilegeVO);
            }
            RedisHelper.setSecRoleFunc(roid, JSONObject.toJSONString(secRoleFuncFDBs));
            RedisHelper.setSecPrivilege(roid, JSONObject.toJSONString(privilegeVOS));
        }
    }

    /**
     * 根据角色编号获取已勾选菜单信息
     *
     * @param roid
     * @return
     */
    public List<SecRoleFunction> querySecRoleFunctionByRoid(Long roid) {
        List<SecRoleFunction> secRoleFuncFDBs = null;
        String jsonStr = RedisHelper.getSecRoleFunc(roid);
        if (StringUtils.isNotBlank(jsonStr)) {
            secRoleFuncFDBs = JSONObject.parseArray(jsonStr, SecRoleFunction.class);//获取所有已勾选的菜单
        } else {
            HashMap params = new HashMap();
            String hql = "from SecRoleFunction where  state=1  ";
            if (NumberUtils.isNotNullOrZero(roid)) {
                hql += " and roid = :roid";
                params.put("roid", roid);
            }
            hql += " order by roid, fid";
            secRoleFuncFDBs = secRoleFunctionDao.find(hql, params);
        }
        return secRoleFuncFDBs;
    }

    /**
     * 保存前数据校验
     *
     * @param secFunc
     * @return
     */
    @Override
    public String checkBeforeSaveOrUpdate(SecFunction secFunc) {
        List<SecFunction> list = querySecFuncByFName(secFunc.getFuncName(), secFunc.getFid());
        if (list != null && !list.isEmpty()) {
            return MessageConstants.DUPLICATE_SECFUNCTION_NAME;
        }
        return MessageConstants.SUCCESS;

    }

    @Override
    public List<String> queryByRoidAndLevel(Long roleId) {
        String sql = "select s.func_url from sec_function s LEFT JOIN sec_role_function r ON s.fid=r.fid where r.state=1 and s.state=1 and s.func_level=3 and r.roid=" + roleId;
        return secRoleFunctionDao.findSqlToString(sql);
    }

    /**
     * 根据菜单编号获取菜单信息
     *
     * @param fName
     * @param fid
     * @return
     */
    public List<SecFunction> querySecFuncByFName(String fName, Long fid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("funcName", fName);
        map.put("fid", fid);
        List<SecFunction> list = secFuncDao.find("from SecFunction where funcName =:funcName and fid<>:fid", map);
        return list;
    }

    /**
     * 根据菜单编号获取菜单信息
     *
     * @param fUrl
     * @param fid
     * @return
     */
    public List<SecFunction> querySecFuncByFUl(String fUrl, Integer fid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("funcUrl", fUrl);
        map.put("fid", fid);
        List<SecFunction> list = secFuncDao.find("from SecFunction where funcUrl =:funcUrl and fid<>:fid", map);
        return list;
    }

    /**
     * 根据角色编号查询菜单
     *
     * @param uid
     * @return
     */
    public List<PrivilegeVO> querySecPrivilege(long uid, long state) {
        List<PrivilegeVO> privilegeVOS = new ArrayList<>();
        List<SecRoleFuncVO> secRoleFuncVOS = this.querySecRoleFuncVOByUid(uid, state);//获取所有菜单

        if (!secRoleFuncVOS.isEmpty()) {
            for (SecRoleFuncVO secRoleFuncVO : secRoleFuncVOS) {//循环一级菜单
                if (secRoleFuncVO == null || secRoleFuncVO.getFristFunc() == null) continue;
                SecFunction secFirst = secRoleFuncVO.getFristFunc();
                if (secFirst == null || !secFirst.getIsChecked()) continue;//一级有权限则赋值，否则跳到下一条
                PrivilegeVO privilegeVO = new PrivilegeVO();
                privilegeVO.setTitle(secFirst.getFuncName());
                privilegeVO.setIcon(secFirst.getFuncPic());
                privilegeVO.setHref(secFirst.getFuncUrl());
                privilegeVO.setName(secFirst.getFuncDesc());
                privilegeVO.setSpread(false);

                if (!secRoleFuncVO.getSecondFuncList().isEmpty()) {
                    List<SecFunction> secSeconds = secRoleFuncVO.getSecondFuncList();
                    List<Privilege> privilegeSeconds = new ArrayList<>();
                    for (SecFunction secSecond : secSeconds) {//循环二级菜单
                        if (secSecond == null || !secSecond.getIsChecked()) continue;//二级有权限则赋值，否则跳到下一条
                        Privilege privilegeSecond = new Privilege();
                        privilegeSecond.setTitle(secSecond.getFuncName());
                        privilegeSecond.setIcon(secSecond.getFuncPic());
                        privilegeSecond.setHref(secSecond.getFuncUrl());
                        privilegeSecond.setName(secSecond.getFuncDesc());
                        privilegeSecond.setSpread(false);
                        privilegeSeconds.add(privilegeSecond);//二级菜单赋值
                    }
                    if (!privilegeSeconds.isEmpty()) {
                        privilegeVO.setChildren(privilegeSeconds);
                    }
                }
                privilegeVOS.add(privilegeVO);
            }
            RedisHelper.setSecPrivilege(uid, JSONObject.toJSONString(privilegeVOS));
        }
        return privilegeVOS;
    }

    /**
     * 增加角色名称校验
     */
    public boolean repeatSecRole(SecRole queryBean) {
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = "select count(*) from SecRole where 1 = 1";
        if (NumberUtils.isNotNullOrZero(queryBean.getRoid())) {
            hql += " and roid <>:roid";
            params.put("roid", queryBean.getRoid());
        }
        if (StringUtils.isNotBlank(queryBean.getRoleName())) {
            hql += " and roleName =:roleName";
            params.put("roleName", queryBean.getRoleName());
        }
        if (NumberUtils.isNotNullOrZero(queryBean.getPartyId())) {
            hql += " and partyId =:partyId";
            params.put("partyId", queryBean.getPartyId());
        }
        long count = secRoleDao.count(hql, params);
        if (count < 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取下拉搜索设备列表
     *
     * @param params
     * @return
     * @throws Exception
     */
    public List<SecRole> querySecRoleTag(HashMap params) throws Exception {
        String hql = "from SecRole where state = 1";
        long partyId = 0;
        if (params != null && params.size() > 0) {
            if (params.get("partyId") != null) {
                partyId = Long.parseLong(params.get("partyId").toString());
            }
        }
        if (NumberUtils.isNotNullOrZero(partyId)) {
            hql += " and partyId = :partyId";
            params.put("partyId", partyId);
        }
        List<SecRole> secRoles = secRoleDao.find(hql, params);
        return secRoles;
    }

    public List<SecFunction> getUserEnableFunction(Long uid) {
        HashMap params = new HashMap();
        String hql = "";

        List<SecFunction> secRoleFunctions = null;
        hql = "select b from SecRoleFunction a , SecFunction b, UserSecRoleRel c " +
                "where  a.state=1 and b.state =1 and c.state = 1 and a.roid = c.roid and a.fid = b.fid and c.uid = :uid and b.funcType = 2";
        params.put("uid", uid);
        secRoleFunctions = secFuncDao.find(hql, params);
        //获取一级菜单信息
        return secRoleFunctions;
    }

    /**
     * 根据用户编号查询菜单分配信息
     *
     * @param uid
     * @return
     */
    public List<SecFunction> querySecRoleFuncVOByUid(long uid) {
        HashMap params = new HashMap();
        String hql = "";

        //获取一级菜单信息
        HashMap params2 = new HashMap();
        List<SecFunction> secFirstFunctions = null;
        String sql = "select * from userdb.sec_function s where fid in (select DISTINCT d.fid from userdb.sec_role_function d where d.roid in ( " +
                "select t.roid  from (" +
                "select a.roid from userdb.sec_role a, userdb.user_sec_role_rel b where a.state = 1 and b.state = 1 and b.uid = :uid and a.roid = b.roid" +
                ") t) ) and s.state = 1 and s.func_type <> 3";
        params2.put("uid", uid);
        sql += " order by sortno, s.fid";
        secFirstFunctions = secFuncDao.findEntityBySql(sql, params2, SecFunction.class);

        if (secFirstFunctions != null) {//一级菜单数据非空
            for (SecFunction secFirstFunction : secFirstFunctions) {//遍历一级菜单
                secFirstFunction.setIsChecked(true);
            }
        }
        return secFirstFunctions;
    }

    /**
     * 根据用户编号获取菜单分配信息(APP)
     *
     * @param uid
     * @return
     */
    public List<SecFunction> querySecRoleFuncVOByUidToApp(long uid) {
        HashMap params = new HashMap();
        String hql = "";
        //获取一级菜单信息
        HashMap params2 = new HashMap();
        List<SecFunction> secFirstFunctions = null;
        String sql = "select * from userdb.sec_function s where fid in (select DISTINCT d.fid from userdb.sec_role_function d where d.roid in ( " +
                "select t.roid  from (" +
                "select a.roid from userdb.sec_role a, userdb.user_sec_role_rel b where a.state = 1 and b.state = 1 and b.uid = :uid and a.roid = b.roid" +
                ") t) ) and s.state = 1 and s.func_type = 3";
        params2.put("uid", uid);
        sql += " order by sortno, s.fid";
        secFirstFunctions = secFuncDao.findEntityBySql(sql, params2, SecFunction.class);

        if (secFirstFunctions != null) {//一级菜单数据非空
            for (SecFunction secFirstFunction : secFirstFunctions) {//遍历一级菜单
                secFirstFunction.setIsChecked(true);
            }
        }
        return secFirstFunctions;
    }
}
